<?php
class Rcp_LpImport_EmployeeImport {
	
	const DEFAULT_CALENDAR = 'GLOWNY';
	
	public function start() {
		$mapUnits = new Rcp_LpImport_EmployeeImport_Units();
		$mapPositions = new Rcp_LpImport_EmployeeImport_Positions();
		$mapUsers = new Rcp_LpImport_EmployeeImport_Users();
		$lpEmployees = LpEmployeesQuery::create()
		->useEmployeesPositionsQuery()
			->useUnitsQuery(null, Criteria::LEFT_JOIN)
				->leftJoinUnitsRelatedByParentId('ParentUnit')
			->endUse()
			->joinPositions()
		->endUse()
		->with('EmployeesPositions')
		->with('Units')
		->with('ParentUnit')
		->with('Positions')
		->find();
		
		$userRoleDefault = RcpRolesQuery::create()->findOneByCode(RcpRoles::CODE_USER);
		$calendar = RcpCalendarsQuery::create()->findOneByName(self::DEFAULT_CALENDAR);
		
		$con = Propel::getConnection('vgp_rcp');
		$con->beginTransaction();
		try {
			foreach ($lpEmployees as $lpEmployee) {
				$updatedUser = $mapUsers->update($lpEmployee);
		
				$lpUnit = $lpEmployee->getEmployeesPositions()->getUnits();
				$lpPosition = $lpEmployee->getEmployeesPositions()->getPositions();
				if ($lpPosition == null) break;
				
				$updatedUnit = $mapUnits->update($lpUnit);
				$updatedUnit->save($con);
				
				$updatedPosition = $mapPositions->update($lpPosition);
				$updatedPosition->save($con);
				
				$updatedUser->setPositions($updatedPosition);
				$updatedUser->setUnits($updatedUnit);
				
				$updatedUser->setIsSuperior($lpUnit->getSupervisorLogoId() == $updatedUser->getExtId());
				
				if ($updatedUser->isNew() || $updatedUser->getUserCalendarss()->count() == 0) {
					$userCalendar = new RcpUserCalendars();
					$userCalendar->setActiveStart(null);
					$userCalendar->setActiveEnd(null);
					$userCalendar->setCalendars($calendar);
					$updatedUser->addUserCalendars($userCalendar);
				}
				
				if ($updatedUser->isNew() || $updatedUser->getUserRoless()->count() == 0) {
					$userRole = new RcpUserRoles();
					$userRole->setRoles($userRoleDefault);
					$userRole->setUsers($updatedUser);
					$userRole->save($con);
				}
				
				$updatedUser->save($con);
			}
			$con->commit();
		} catch (Exception $e) {
 			$con->rollBack();
 			throw $e;
 		}
		
	}
	
}